from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from services.Models import KnownUser, Playlist, Properties


class MainPage(webapp.RequestHandler):    
    
    def get(self):       

        user = users.get_current_user()
        if user: #if user is signed in      
            
            userCheck = KnownUser.gql("WHERE kuser = :1", users.get_current_user()).count()
            if (userCheck == 0): 
                knownuser = KnownUser()
                knownuser.kuser = users.get_current_user()
                knownuser.isNew = True                
                properties = Properties()
                properties.user = users.get_current_user().email()
                properties.recieveEmails = True
                properties.findAlternatives = True
                properties.put()
                knownuser.put()               
                newplaylist = Playlist()
                newplaylist.name = 'All'
                newplaylist.isDefault = True
                newplaylist.user = users.get_current_user()
                newplaylist.put()
 
            self.redirect(self.request.uri + 'youTunesTemplate.html')
            
        else:
            self.redirect(self.request.uri + 'home.html')

class LoginPage(webapp.RequestHandler):  

    def get(self):
        url = 'http://youtunes-tau2010.appspot.com/'        
        self.redirect(users.create_login_url(url))

application = webapp.WSGIApplication([('/', MainPage), ('/login', LoginPage)], debug=True)

def main():
    run_wsgi_app(application)


if __name__ == "__main__":
    main()
